package site.hugboy.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import site.hugboy.reggie.common.R;
import site.hugboy.reggie.entity.Employee;
import site.hugboy.reggie.service.EmployeeService;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //* 1、将页面提交的密码password进行md5加密处弹
        String pw = employee.getPassword();
        pw = DigestUtils.md5DigestAsHex(pw.getBytes());

        //* 2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(qw);
        //* 3、如果没有查询到则返回登录失败结果
        if (emp == null) {
            return R.error("账号或密码错误.");
        }
        //* 4、密码比对，如果不一致则返回登录失败结果
        if (!emp.getPassword().equals(pw)) {
            return R.error("账号或密码错误.");
        }
        //* 5、查看员工状态，如果为已禁用状态，则返回员工己禁用结果
        if (emp.getStatus() == 0) {
            return R.error("账号已禁用.");
        }
        //* 6、登录成功，将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     *
     * @param req
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest req) {

        log.info("清除session前。。。。。。。。。。。。。。。");
        System.out.println(req.getSession().getAttribute("employee"));
        // 清除Session保存的id
        req.getSession().removeAttribute("employee");
        log.info("清除session后。。。。。。。。。。。。。。。");
        System.out.println(req.getSession().getAttribute("employee"));
        return R.success("退出成功.");
    }

    /**
     * 新增员工
     *
     * @param emp
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest req, @RequestBody Employee emp) {
        log.info("新增员工:{}", emp.toString());
//        设置初始密码
        emp.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
//        emp.setCreateTime(LocalDateTime.now());
//        emp.setUpdateTime(LocalDateTime.now());
//        获得当前登录用户的id
//        Long empId = (Long) req.getSession().getAttribute("employee");
//
//        emp.setCreateUser(empId);
//        emp.setUpdateUser(empId);
        employeeService.save(emp);
        return R.success("保存成功.");
    }

    /**
     * 员工一览分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page={}, pageSize = {}, name = {}", page, pageSize, name);

        // 构造分页构造器
        Page p = new Page(page, pageSize);

        // 构造条件构造器
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper();
        qw.like(!StringUtils.isEmpty(name), Employee::getName, name);
        // 添加排序条件
        qw.orderByDesc(Employee::getUpdateTime);

        // 执行查询
        employeeService.page(p, qw);
        return R.success(p);
    }

    /**
     * 根据 id 修改员工信息
     *
     * @param emp
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest req, @RequestBody Employee emp) {
        log.info(emp.toString());

//        emp.setUpdateTime(LocalDateTime.now());
//        Long empId = (Long) req.getSession().getAttribute("employee");
//        emp.setUpdateUser(empId);
        employeeService.updateById(emp);

        return R.success("员工信息修改成功.");
    }

    /**
     * 根据id 查询员工信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getOneById(@PathVariable Long id) {
        log.info("根据id 查询员工信息...........");
        Employee emp = employeeService.getById(id);
        if (emp == null) {
            return R.error("员工[ " + id + " ]不存在.");
        }
        return R.success(emp);
    }
}
